'use strict';

var _ = require('underscore');
var suquelizeService = require('../utils/sequelizeService');
var auth = require('../authControllers/user');
var Article = suquelizeService.models.Article;
var resJson = require('../utils/resJson.js');
var Promise = require('bluebird');

//统计阅读次数
var setReadCount = function(req, res, next) {
  var id = parseInt(req.params.id);
  if (id) {
    //达到n个ip时，先清空数组
    if (_.size(ipArt) >= 3000) {
      ipArt = {};
    }
    //获取客户端ip
    var ip = req.ip.match(/\d+\.\d+\.\d+\.\d+/);
    ip = ip ? ip[0] : '';
    var now = Date.now();
    var duration = 0;
    if (!_.has(ipArt, ip)) {
      ipArt[ip] = {};
      ipArt[ip][id] = now;
    } else {
      duration = ipArt[ip][id] ? now - ipArt[ip][id] : 0;
      ipArt[ip][id] = now;
    }

    //距离上次访问大于2小时才增加阅读次数
    if (duration === 0 || duration >= 7200000) {
      Article.findById(id)
        .then(function(_art) {
          if (_art) {
            _art.update({ readCount: (_art.readCount || 0) + 1 });
          }
        });
    }
  }
  next();
};

var controller = {

};
var ipArt = {};



//获取文章
controller.getArticles = {
  route: 'articles',
  filter: setReadCount,
  paramUrl: ['', '/:id'],
  action: function(req, res, next) {
    //没有带任何参数，通过url参数条件获取
    var getArt = null;
    if (_.isEmpty(req.params)) {
      var categoryCode = req.query.code || null;
      var page = parseInt(req.query.page) || null;
      var size = parseInt(req.query.size) || null;
      var search = req.query.search || null;
      getArt = Article.fetchPage({
        page: page,
        size: size,
        search: search,
        categoryCode: categoryCode
      });
    } else {
      var id = parseInt(req.params.id);
      //通过id获取
      if (id) {
        getArt = Article.findById(id);
      } else {
        return resJson(res, null, '错误的参数');
      }
    }
    getArt
      .then(function(_result) {
        return resJson(res, _result);
      })
      .catch(function(err) {
        return resJson(res, null, err);
      });
  }
};

//删除文章
controller.delArticles = {
  method: 'delete',
  route: 'articles',
  paramUrl: '/:id',
  filter: auth.loginCheckByAjax,
  action: function(req, res, next) {
    var id = parseInt(req.params.id);
    if (id) {
      Article.destroy({ where: { id: id } })
        .then(function(_art) {
          return resJson(res, _art);
        })
        .catch(function(err) {
          return resJson(res, null, err);
        });
    }
  }
};

//修改文章
controller.updArticles = {
  method: 'put',
  route: 'articles',
  paramUrl: '/:id',
  filter: auth.loginCheckByAjax,
  action: function(req, res, next) {
    var id = parseInt(req.params.id);
    if (id && !_.isEmpty(req.body)) {
      var input = req.body;
      Article.findById(id)
        .then(function(_art) {
          if (!_art) {
            return Promise.reject(new Error("文章已被删除！"));
          } else {
            return _art.update(input);
          }
        })
        .then(function(_art) {
          return resJson(res, _art);
        })
        .catch(function(err) {
          return resJson(res, null, err);
        });
    } else {
      return resJson(res, null, '错误的参数');
    }
  }
}

//新增文章
controller.insArticles = {
  method: 'post',
  route: 'articles',
  filter: auth.loginCheckByAjax,
  action: function(req, res, next) {
    console.log(req.originalUrl);
    if (!_.isEmpty(req.body)) {
      var input = req.body;
      Article.create(input)
        .then(function(_art) {
          return resJson(res, _art);
        })
        .catch(function(err) {
          return resJson(res, null, err);
        });
    } else {
      return resJson(res, null, '错误的参数');
    }
  }
}

//获取阅读数
controller.getReadCount = {
  method: 'post',
  route: 'articles/readcount',
  action: function(req, res, next) {
    console.log(req.body);
    if (!req.body.idArray) {
      return resJson(res, null, "错误的参数");
    } else {
      Article.findAll({
          where: {
            id: {
              $in: req.body.idArray
            }
          },
          attributes: ['id', 'readCount']
        })
        .then(function(_art) {
          return resJson(res, _art);
        })
        .catch(function(err) {
          return resJson(res, null, err);
        });
    }
  }
};

module.exports = controller;